package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.MainProductionMapper;
import com.koocloud.electroplatemanage.mapper.ProductCompletedMapper;
import com.koocloud.electroplatemanage.mapper.ProductionTaskMapper;
import com.koocloud.electroplatemanage.pojo.ProductionTask;
import com.koocloud.electroplatemanage.pojo.WorkProcessVo;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.ProductCompletedService;
import com.koocloud.electroplatemanage.utils.ListUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.WORKCOMPLETED;

/**
 * @program: Information_platform
 * @description: 生产完工实现层
 * @author: xxc
 * @create: 2020-11-23 10:43
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ProductCompletedServiceImpl implements ProductCompletedService {
    @Resource
    private IUserDao iUserDao;
    @Resource
    private ProductCompletedMapper productCompletedMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private ProductionTaskMapper productionTaskMapper;
    Lock lock = new ReentrantLock();

    /**
     *@Description: 通过工单号查询一条记录
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumber(String workOrderNumber) {
        try {
            LinkedHashMap linkedHashMap = productCompletedMapper.selectByWorkOrderNumber(workOrderNumber);
            //判断查表操作是否成功
            if (!StringUtils.isEmpty(linkedHashMap)) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(linkedHashMap).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 查询所有记录 分页
     *@Param: [page, limit, idOrName]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, String idOrName) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try{
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为6的插入生产
                List<WIP> wipList = mainProductionMapper.selectAllWIPByLocation(WORKCOMPLETED);
                if(!ListUtil.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //创建实体
                            LinkedHashMap linkedHashMap = new LinkedHashMap();
                            //设置工单号
                            linkedHashMap.put("workOrderNumber",wip.getWorkOrderNumber());
                            //数据库重复工单号校验
                            int count = productCompletedMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }
                            //获取当前单据数量，即任务单的任务数量
                            ProductionTask productionTask = productionTaskMapper.selectByWorkOrderNumber(wip.getWorkOrderNumber());
                            if(!StringUtils.isEmpty(productionTask)){
                                //设置当前单据数量
                                linkedHashMap.put("currentQuantity",productionTask.getTaskQuantity());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置生产完成时间
                                linkedHashMap.put("productCompletedTime",wip.getEntryTime());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置生产操作人
                                linkedHashMap.put("operator",wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                linkedHashMap.put("createTime",wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                linkedHashMap.put("creator",wip.getEntryPerson());
                            }
                            //记录成功插入条数
                            rows = productCompletedMapper.insert(linkedHashMap);
                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //全局查询
                    List<LinkedHashMap> linkedHashMapList = productCompletedMapper.selectAllData(idOrName);
                    //构造分页实体
                    PageInfo<LinkedHashMap> info=new PageInfo<>(linkedHashMapList);
                    if (info.getTotal()>0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                } else {
                    return ResponseTemplate.builder().code(1).message("主要工序表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        } else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description: 修改一条记录
     *@Param: [linkedHashMap, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/23
     */
    @Override
    public ResponseTemplate update(LinkedHashMap linkedHashMap, String userId) {
        try {
            lock.lock();
            //没有异常并且修改数据条数大于0
            int rows = productCompletedMapper.update(linkedHashMap);
            if(rows>0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
}
